<template>
    <rx-layout>
        <div slot="left" width="250" showButton="true">
            <rx-fit>
                <rx-category-treeeditor
                    cat-key="FORM"
                    :statisticConfig="statisticConfig"
                    :edit="true"
                    @handSelect="handSelect"
                    :async="true"
                    v-if="isShowManageTree"
                    :isAdmin="isManageToTree"
                    :checkToDel="true"
                ></rx-category-treeeditor>
            </rx-fit>
        </div>
        <div slot="center" style>
            <rx-fit :isheader="isheader">
                <div slot="toolheader" foldheader="true" foldbtn="false" border="false">
                    <div class="table-operator">
                        <a-button type="primary" icon="plus" v-if="findAuthRight('add')" @click="add">
                            {{$ti18('rxList.newBtn','新建')}}
                        </a-button>
                        <a-button type="primary" v-if="!isAppDevelop && selectedRowKeys.length > 0 " icon="redo"
                                  @click="changeApp('FORM',selectedRows,'pkId','name','appId','treeId',changeAppId)">
                            {{i18n('list.changeApp','变更应用')}}
                        </a-button>
                        <a-button v-if="selectedRowKeys.length > 0"
                                  type="primary"
                                  icon="switcher" @click="openCategoryDialog">
                            {{$ti18('rxList.changeCategory','切换分类')}}
                        </a-button>
                        <a-dropdown>
                            <a-button>
                                {{i18n('list.more','更多')}}
                                <a-icon type="down"/>
                            </a-button>
                            <a-menu slot="overlay">
                                <a-menu-item key="1" @click="doImport" v-if="findAuthRight('add')"><i
                                    class="iconfont icondaoru"></i>
                                    {{$ti18('rxList.importBtn','导入')}}
                                </a-menu-item>
                                <a-sub-menu>
                                    <span slot="title"><i class="iconfont icondaochu"></i>
                                    {{$ti18('rxList.exportBtn','导出')}}</span>
                                    <a-menu-item @click="doExport('0')"><i class="iconfont icondaochu"></i>
                                        {{i18n('list.exportAll','导出当前所有')}}
                                    </a-menu-item>
                                    <a-menu-item @click="doExport('1')"><i class="iconfont icondaochu"></i>
                                        {{i18n('list.exportSelected','导出所选中')}}
                                    </a-menu-item>
                                </a-sub-menu>
                                <a-menu-item
                                    key="2"
                                    @click="editOne"
                                    v-if="findAuthRight('edit') && editEnable && selectedRowKeys.length > 0"
                                    alias="formRuleEdit"
                                    :butn-type="'primary'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="edit"/>
                                    {{$ti18('rxList.editBtn',"编辑")}}
                                </a-menu-item>
                                <a-menu-item
                                    key="3"
                                    @click="delByIds(selectedRowKeys)"
                                    v-if="findAuthRight('delete') && removeEnable && selectedRowKeys.length > 0"
                                    alias="formRuleDelete"
                                    :butn-type="'danger'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="delete"/>
                                    {{$ti18('rxList.delBtn','删除')}}
                                </a-menu-item>
                                <a-menu-item
                                    key="4"
                                    @click="changeExport(exportConf)"
                                    v-if="selectedRowKeys.length > 0"
                                    alias="formRuleDelete"
                                    :butn-type="'primary'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="switcher"/>
                                    {{$ti18('rxList.changeExport','切换导出')}}
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </div>
                    <span class="search-btn-box" v-if="!isheader">
            <span class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>
            {{$ti18('rxList.leachBtn','过滤')}}
            </span>
          </span>
                </div>
                <div btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel"
                     @close="closeSearchbar">
                    <a-form :layout="colLayout">
                        <a-row :gutter="24">
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.name','名称')">
                                    <a-input :placeholder="i18n('form.name','名称','input')" v-model="queryParam.Q_NAME__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.identificationName','标识名')">
                                    <a-input :placeholder="i18n('form.identificationName','标识名','input')"v-model="queryParam.Q_KEY__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan" v-if="!curApp.appId">
                                <a-form-item :label="$ti18('rxForm.appId', '应用')">
                                    <rx-search-app @change="appChange" v-model="searchApps">
                                    </rx-search-app>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <rx-grid
                    ref="table"
                    :bordered="isBorder"
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :columns="columns"
                    :defaultPageSize="10"
                    url="/api-form/form/core/formCustomQuery/query"
                    :queryParam="queryParam"
                    data-field="result.data"
                    :pageSizeOptions="['10','30','40']"
                    id-field="id"
                    :loadDataOnstart="true"
                    @selectChange="onSelectChange"
                >
                    <span slot="exportApp">
                         {{ exportI18n('export.isExport','导出') }}
                        <export-app/>
                    </span>
                    <span slot="appId" slot-scope="{ text, record }">
                        {{allApps[text]?$i18(allApps[text].appName,'应用名称'):$ti18('rxList.noAppName','无')}}
                    </span>
                    <span slot="isExport" slot-scope="{ text, record }">
                        <a-tag :color="text == 1 ? 'green' : 'red'">
                             <span>{{ text == 1 ? exportI18n('export.yes','是') : exportI18n('export.no','否') }}</span>
                        </a-tag>
                    </span>
                    <span slot="action" slot-scope="{ text, record }" class="actionIcons">
                        <span v-if="findAuthRight('edit') && editEnable" @click.stop="edit(record)">
                            {{$ti18('rxList.editBtn',"编辑")}}
                        </span>
                        <span v-if="findAuthRight('delete') && removeEnable" @click.stop="delByIds([record.id])">
                            {{$ti18('rxList.delBtn','删除')}}
                        </span>
                        <span @click.stop="preview([record.id])">
                            {{$ti18('rxList.previews','预览')}}
                        </span>
                        <span @click.stop="helpView([record.id])">
                            {{i18n('form.help','帮助')}}
                        </span>
                        <span :title="i18n('form.genExternalApi','生成对外接口')" @click.stop="genExternalApi([record])">
                            {{i18n('form.genExternalApi','生成对外接口')}}
                        </span>
                         <span @click="setExport(record,exportConf)">{{record.isExport == 1 ? exportI18n('export.noExport','不导出') : exportI18n('export.exported','导出')}}</span>
                         <span v-if="!curApp.appId" @click="share(record)">{{$ti18('rxList.share','共享')}}</span>
                    </span>
                </rx-grid>
            </rx-fit>
        </div>
    </rx-layout>
</template>

<script>
    import FormCustomQueryApi from '@/api/form/core/formCustomQuery'
    import FormCustomQueryEdit from './FormCustomQueryEdit'
    import FormCustomQueryPreview from './FormCustomQueryPreview'
    import FormCustomQueryHelp from './FormCustomQueryHelp'
    import FormImport from './FormImport'
    import {BaseList, Util, RxLayout,Dialog} from "@lowcode/jpaas-common-lib"
    import RxCategoryTreeeditor from "@/components/redxun/rx-category-treeeditor";
    import SysExternalApiApi from "@/api/system/core/sysExternalApi";
    import changeAppJs from "@/views/modules/share/changeApp";
    import {mapState} from "vuex";
    import exportApp from "@/views/modules/share/exportApp";
    import FormResourceShareApi from "@/api/form/core/formResourceShare";
    import AppSearch from "@/views/modules/share/AppSearch";
    import RxSearchApp from "@/views/modules/share/rx-search-app";
    import switchExport from "@/utils/switchExport";
    import ChangeCategory from "@/views/modules/share/ChangeCategory.js"

    export default {
        name: 'FormCustomQueryList',
        mixins: [BaseList,changeAppJs,AppSearch,switchExport,ChangeCategory],
        components: {
            RxLayout,
            RxCategoryTreeeditor,
            FormImport,
            exportApp,
            RxSearchApp
        },
        computed: {
            ...mapState({
                //所属应用
                allApps: state => state.appSetting ? state.appSetting.allApps : {}
            }),
        },
        data() {
            return {
                columns: [
                    {
                        title: this.$ti18('rxList.index','序号'),
                        type: 'indexColumn',
                        width: 50,
                        dataIndex: 'serial',
                        scopedSlots: {customRender: 'serial'}
                    },
                    {title: this.i18n('form.name','名称'), dataIndex: 'name', width: 140},
                    {title: this.i18n('form.identificationName','标识名'), dataIndex: 'key', width: 120},
                    {title: this.i18n('form.tableOrView','表或视图'), dataIndex: 'tableName', width: 120},
                    {title: this.i18n('form.application','所属应用'), dataIndex: 'appId', width: 100, sortField: 'APP_ID_',scopedSlots: {customRender: 'appId'}},
                    {
                        dataIndex: 'isExport',
                        slots: { title: 'exportApp' },
                        width: 100,
                        scopedSlots: {customRender: 'isExport'}
                    },
                    {title: this.i18n('form.createTime','创建时间'), dataIndex: 'createTime', width: 150},
                    {title: this.$ti18('rxList.action','操作'), dataIndex: 'action', scopedSlots: {customRender: 'action'},
                        width:Util.langSize({'zh-CN':120,'en-US':140,'ja-JP':140,'es-ES':180})
                    }
                ],
                component: FormCustomQueryEdit,
                comment: this.i18n('form.customQuery','自定义查询'),
                help: this.i18n('form.help','帮助'),
                curTree: {},
                max:true,
                statisticConfig: {
                    type:"static_form",
                    table:"FORM_CUSTOM_QUERY t",
                    field:"TREE_ID_",
                    whereConf:[]
                },
                /**
                 * 导出配置
                 */
                exportConf:{
                    Api:FormCustomQueryApi,
                    id:"id"
                },
                //变更分类配置
                categoryConfig:{
                    Api:FormCustomQueryApi,
                    catKey:"FORM",
                    gridRef:"table"
                }
            }
        },
        created() {
            this.isUserManager(this.$route.query.appId);
            this.needFilterAppId("isAppMenu");
            this.columns=this.removeAppColumn(this.curApp.appId,this.columns)
        },
        methods: {
            i18n(name,text,key){
                return this.$ti18(name,text,"formCustomQuery",key);
            },
            exportI18n(name,text,key){
                return this.$ti18(name,text,"appExport",key);
            },
            //资源共享
            share(record){
                let self=this;
                FormResourceShareApi.getShareApps(record.id).then(res => {
                    let initData=res.data;
                    if(!initData){
                        initData=[];
                    }
                    self.showAppDialog(initData,record.id,record.key,record.name);
                });
            },
            showAppDialog(initData,resId,resKey,resName){
                Dialog.openSystemAppDialog({
                    curVm: this, widthHeight: ['1150px', '735px'],
                    data:{initSelected: initData,isDevelopApp:true,isSelectApp:true}
                }, function (self, data) {
                    //保存共享信息
                    FormResourceShareApi.saveShareApps(data.apps,resId,resKey,resName,"1").then(res => {
                        if (res.success && res.code == 200) {
                        }
                    });
                })
            },
            delById(ids) {
                return FormCustomQueryApi.del({ids: ids.join(',')})
            },
            getListByParams(parameter) {
                return FormCustomQueryApi.query(parameter)
            },
            //打开帮助
            helpView(pkId) {
                var self = this;
                var conf = {
                    component: FormCustomQueryHelp,
                    title: this.help,
                    widthHeight: this.widthHeight
                }
                var baseConf = {
                    curVm: self,
                    data: {pkId: pkId}
                }
                let config = Object.assign(baseConf, conf)
                Util.open(config, function (action) {
                })

            },
            preview(pkId) {
                var self = this;
                var conf = {
                    component: FormCustomQueryPreview,
                    title: this.$ti18('rxList.previews','预览') + this.comment,
                    widthHeight: this.widthHeight
                }
                var baseConf = {
                    curVm: self,
                    data: {pkId: pkId}
                }
                let config = Object.assign(baseConf, conf)
                Util.open(config, function (action) {
                    if (action == 'ok') {
                        self.$refs.table.loadData()
                    }
                })
            },
            doExport(isSelected) {
                var exportList = [];
                if (isSelected == "1") {
                    exportList = this.$refs.table.getSelectedRows();
                    if (!exportList || exportList.length == 0) {
                        this.$warning({
                            title: this.i18n('form.warning','警告'),
                            content: this.i18n('form.selectRecord','需要导出的记录！','select'),
                        });
                        return;
                    }
                } else {
                    exportList = this.$refs.table.dataAction;
                }

                if (exportList == "") {
                    this.$warning({
                        title: this.i18n('form.warning','警告'),
                        content: this.i18n('form.noData','该分类没有数据！'),
                    });
                    return;
                }

                var solutionIds = [];
                exportList.forEach(item => {
                    solutionIds.push(item.id);
                });
                FormCustomQueryApi.doExport(solutionIds);
            },
            doImport() {
                if (!this.curTree || !this.curTree.treeId) {
                    this.$warning({
                        title: this.i18n('form.warning','警告'),
                        content: this.i18n('form.classification','自定义SQL查询的分类!','select'),
                    });
                    return;
                }
                var treeId = this.curTree.treeId;
                Util.open({
                    component: FormImport,
                    curVm: this,
                    widthHeight: ['800px', '600px'],
                    title: this.i18n('form.custom','自定义SQL导入'),
                    data: {
                        treeId: treeId,
                        callback: function (params) {
                            let self = this;
                            FormCustomQueryApi.doImport(params).then(res => {
                                this.isSpinning = false;
                                if (!res.success) {
                                    return;
                                }
                                //self.$message.info(this.i18n('form.importOk','导入成功！'));
                                self.getUpdataSqls(res.data);
                            });
                        }
                    }
                }, function (action) {
                });
            },
            handSelect(curRow) {
                this.curTree = curRow
                var treeId = curRow.treeId;
                if (treeId != "0") {
                    this.queryParam.Q_TREE_ID__S_EQ = treeId;
                } else {
                    delete this.queryParam.Q_TREE_ID__S_EQ;
                }
                this.loadData(this.queryParam);
            },
            search() {
                this.$refs.table.loadData();
            },
            cancel() {
                this.resetSearch();
            },
            closeSearchbar() {
                //关闭过滤弹窗；（点击X触发）
                this.fitSearch = false;
            },
            genExternalApi(selectedRows) {
                if(!selectedRows || selectedRows.length==0){
                    this.$message.warning(this.i18n('form.leastOne','请至少选择一条数据!'));
                    return;
                }
                var ary=[];
                for (let i = 0; i < selectedRows.length; i++) {
                    ary.push(selectedRows[i].key);
                }
                this.selectCategory("EXTERNAL_API", function (categoryId){
                    SysExternalApiApi.genExternalApi({alias: ary.join(","),type:"sql",categoryId:categoryId});
                });
            },
            changeAppId(selectedRows){
                FormCustomQueryApi.saveList(selectedRows);
            }
        }
    }
</script>
<style scoped>
</style>


